package com.hxh.util;


import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

@Data
@NoArgsConstructor
public class DirClone {

    //源路径
    private String sourse;
    //目标路径
    private String target;

    public DirClone(String sourse, String target){
        this.sourse = sourse;
        this.target = target;
    }

    public void Clone(String url) {
        Clone(url,false);
    }

    /**
     * 遍历文件夹并复制
     */
    public void Clone(String url,boolean isAbsolutePath) {
        //获取目录下所有文件
        File f = new File(url);
        File[] allf = f.listFiles();

        //遍历所有文件
        for (File fi : allf) {
            try {
                //拼接目标位置
                String URL;
                if (isAbsolutePath){
                    URL= target + fi.getAbsolutePath().substring(sourse.length());
                }else{
                    URL = target + fi.getPath().substring(sourse.length());
                }
                //创建目录或文件
                if (fi.isDirectory()) {
                    Createflies(URL);
                } else {
                    fileInputOutput(fi.getAbsolutePath(), URL);
                }

                //递归调用
                if (fi.isDirectory()) {
                    Clone(fi.getPath());
                }

            } catch (Exception e) {
                System.out.println("error");
            }
        }
    }

    /**
     * 复制文件
     *
     * @param sourse
     * @param target
     */
    public static void fileInputOutput(String sourse, String target) {
        try {
            File s = new File(sourse);
            File t = new File(target);

            if (t.isDirectory() && !t.exists()) {
                t.mkdirs();
            }

            if (!t.exists()) {
                if (!t.getParentFile().exists()) {
                    t.getParentFile().mkdirs();
                }
                t.createNewFile();
            }

            FileInputStream fin = new FileInputStream(s);
            FileOutputStream fout = new FileOutputStream(t);

            byte[] a = new byte[1024 * 1024 * 4];
            int b = -1;

            //边读边写
            while ((b = fin.read(a)) != -1) {
                fout.write(a, 0, b);
            }
            fout.close();
            fin.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 创建目录
     *
     * @param name
     * @return
     */
    public static boolean Createflies(String name) {
        boolean flag = false;
        File file = new File(name);
        //创建目录
        if (file.exists()){
            return true;
        }
        if (file.mkdirs() == true) {
            System.out.println("文件夹创建成功！");
            flag = true;
        } else {
            System.out.println("文件夹创建失败！");
            flag = false;

        }
        return flag;
    }
}